﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using Baidu.Api.Util;

namespace BaiduTestForm
{
    public class FileBlock
    {
        private int bufferSize = 1024 * 512;
        public FileInfo fileInfo { get; protected set; }
        public List<string> BlockList { get; set; }

        #region create

        /// <summary>
        /// 基于本地文件的构造器。
        /// </summary>
        /// <param name="fileInfo">本地文件</param>
        public FileBlock(FileInfo fileInfo)
        {
            if (fileInfo == null || !fileInfo.Exists)
            {
                throw new ArgumentException("fileInfo is null or not exists!");
            }
            this.fileInfo = fileInfo;
        }

        /// <summary>
        /// 基于本地文件全路径的构造器。
        /// </summary>
        /// <param name="filePath">本地文件全路径</param>
        public FileBlock(string filePath)
            : this(new FileInfo(filePath))
        { }

        #endregion

        public static FileBlock LoadFromTxt(string txtfile)
        {
            var lines = System.IO.File.ReadAllLines(txtfile);
            if (lines == null || lines.Length == 0) return null;
            var file = new FileBlock(lines.First());
            file.BlockList = lines.Skip(1).ToList();
            return file;
        }

        public void SaveToTxt(string path)
        {
            System.IO.File.WriteAllLines(path, new[] { fileInfo.FullName }.Concat(BlockList));
        }

        public IEnumerable<byte[]> GetBytesByBlockCount(int blockCount)
        {
            if (this.fileInfo != null && this.fileInfo.Exists)
            {
                long position = blockCount * bufferSize;
                if (position < this.fileInfo.Length)
                {
                    return GetBytes(position);
                }
            }

            return null;
        }

        private IEnumerable<byte[]> GetBytes(long position = 0)
        {
            int read;
            byte[] content = new byte[bufferSize];

            using (System.IO.Stream fileStream = this.fileInfo.OpenRead())
            {
                fileStream.Position = position;
                while ((read = fileStream.Read(content, 0, content.Length)) > 0)
                {
                    yield return content.Take(read).ToArray();
                }
            }
        }
    }
}
